import NavBar from '@/components/NavBar'
import { DatePicker, Drawer, List, Modal, Toast } from 'antd-mobile'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { useEffect, useRef, useState } from 'react'
import {
  editProfile,
  getProfile,
  logout as logoutAction,
  updatePhoto
} from '@/store/actions/profile'
import InputEdit from '@/pages/Profile/Edit/components/InputEdit'
import EditList from '@/pages/Profile/Edit/components/EditList'

const ProfileEdit = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const profile = useSelector((state) => state.profile.profile)
  const fileRef = useRef(null)
  const [open, setOpen] = useState(false)
  const [openType, setOpenType] = useState('')
  const [listOpen, setListOpen] = useState({
    visible: false,
    type: ''
  })

  useEffect(() => {
    dispatch(getProfile())
  }, [dispatch])

  // 控制名字简介打开
  const onClose = () => {
    setOpen(false)
    setOpenType('')
  }
  // 控制性别/照片打开
  const listVisibleClose = () => {
    setListOpen({
      visible: false,
      type: ''
    })
  }
  // 点击修改用户资料
  const handleSubmit = async (type, value) => {
    await dispatch(editProfile(type, value))
    Toast.success('更新成功')

    onClose()
  }
  // 处理文件上传
  const handleFileUpload = async (e) => {
    const file = e.target.files[0]
    const fromData = new FormData()
    fromData.append('photo', file)
    await dispatch(updatePhoto(fromData))
    Toast.success('更新成功')
    listVisibleClose()
  }
  const config = {
    photo: [
      {
        title: '拍照',
        onClick: () => {
          fileRef.current.click()
        }
      },
      {
        title: '本地上传',
        onClick: () => {
          fileRef.current.click()
        }
      }
    ],
    gender: [
      {
        title: '男',
        onClick: async () => {
          await dispatch(editProfile('gender', 0))
          Toast.success('更新成功', 3, null, false)
          listVisibleClose()
        }
      },
      {
        title: '女',
        onClick: async () => {
          await dispatch(editProfile('gender', 1))
          Toast.success('更新成功', 3, null, false)
          listVisibleClose()
        }
      }
    ]
  }

  // 选择生日
  const handleDateChange = async (date) => {
    const y = date.getFullYear()
    const m = date.getMonth()
    const day = date.getDate()
    await dispatch(editProfile('birthday', `${y}-${m}-${day}`))
    Toast.success('修改成功')
  }

  // 退出
  function handleLogout() {
    Modal.alert('退出', '你确认退出吗?', [
      { text: '取消', onPress: () => console.log('cancel') },
      {
        text: '确定',
        onPress: async () => {
          await dispatch(logoutAction())
          history.push('/login')
        }
      }
    ])
  }
  return (
    <div className={styles.root}>
      <div className='content'>
        {/* 顶部导航栏 */}
        <NavBar onLeftClick={() => history.go(-1)}>个人信息</NavBar>

        <div onClick={() => history.push('/login')}>去登陆</div>

        <div className='wrapper'>
          {/* 列表一：显示头像、昵称、简介 */}
          <List className='profile-list'>
            <List.Item
              arrow='horizontal'
              extra={
                <span className='avatar-wrapper'>
                  <img src={profile.photo} alt='' />
                </span>
              }
              onClick={() =>
                setListOpen({
                  visible: true,
                  type: 'photo'
                })
              }>
              头像
            </List.Item>

            <List.Item
              arrow='horizontal'
              extra={profile.name}
              onClick={() => {
                setOpen(true)
                setOpenType('name')
              }}>
              昵称
            </List.Item>

            <List.Item
              arrow='horizontal'
              extra={
                <span
                  className='intro'
                  onClick={() => {
                    setOpen(true)
                    setOpenType('intro')
                  }}>
                  {profile.intro || '未填写'}
                </span>
              }>
              简介
            </List.Item>
          </List>

          {/* 列表二：显示性别、生日 */}
          <List className='profile-list'>
            <List.Item
              arrow='horizontal'
              extra={profile.gender ? '女' : '男'}
              onClick={() =>
                setListOpen({
                  visible: true,
                  type: 'gender'
                })
              }>
              性别
            </List.Item>
            <DatePicker
              mode='date'
              title='选择年月日'
              value={new Date(profile.birthday)}
              minDate={new Date(1900, 1, 1, 0, 0, 0)}
              maxDate={new Date()}
              onChange={handleDateChange}>
              <List.Item arrow='horizontal' extra={profile.birthday}>
                生日
              </List.Item>
            </DatePicker>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input
            type='file'
            hidden
            ref={fileRef}
            onChange={handleFileUpload}
            accept='image/*'
          />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className='logout'>
          <button className='btn' onClick={() => handleLogout()}>
            退出登录
          </button>
        </div>
      </div>

      {/*昵称和简介的弹出框*/}
      <Drawer
        children={''}
        sidebar={
          open && (
            <InputEdit
              key={openType}
              onClose={onClose}
              onSubmit={handleSubmit}
              type={openType}></InputEdit>
          )
        }
        open={open}
        className={'drawer'}
      />
      {/*  性别弹出框*/}
      <Drawer
        children={''}
        sidebar={
          <EditList
            config={config}
            type={listOpen.type}
            listVisibleClose={listVisibleClose}
          />
        }
        className='drawer-list'
        position='bottom'
        onOpenChange={listVisibleClose}
        open={listOpen.visible}
      />
    </div>
  )
}

export default ProfileEdit
